A method with named arguments

The method with named arguments will allow passing the argument to the methods' parameter during the method call where each of the arguments is matched one by one to the method parameters. You will see the example below of passing the arguments with Function declaration and definition along with the method call in action:
object demo {
def funSub(x:Int, y:Int) : Int =
{
var diff:Int = 0
diff = x - y
// return value
return diff
}
def main(args: Array[String]) {
// Function call
println("Difference of the value is: " + funSub(6,8));
println("Difference of the value is " + funSub(y=6,x=8));
}
}
The above program contains a method named as 'funSub' with both the parameters x and y having return type as 'Int,' the overall return type of the method is 'Int'. It is followed by an assignment statement to assign the return value. The curly braces indicate the start of the method body, where the variable 'diff' is initialized with the initial value of 0. The Method call 'funSub(8,6)' done in the main method matches 8 to 'x' and 6 to 'y,' and the subtraction operation is carried out, and the value of 'diff' is returned and finally gets printed. Similarly, the 'funSub(x=8,y=6)' matches 6 to 'y' and 8 to 'x' to parameters in the method during method call where the order doesn't matter where a similar operation is done and is return and result gets printed out.

Method with with named parameters
In scala function, you can specify the names of parameters during calling the function. In the given example, you can notice that parameter names are passing during calling. You can pass named parameters in any order and can also pass values only.

object demo {
def main(args: Array[String]) = {
var result1 = functionExample(a = 15, b = 2) // Parameters names are passed during call
var result2 = functionExample(b = 15, a = 2) // Parameters order have changed during call
var result3 = functionExample(15,2) // Only values are passed during call
println(result1+"\n"+result2+"\n"+result3)
}
def functionExample(a:Int, b:Int):Int = {
a+b
}
Output:
17
17
17

No comments:

Post a Comment